package com.lvcoding.sec3.secdemo3.security.sms;

import cn.hutool.core.util.StrUtil;
import com.lvcoding.sec3.secdemo3.security.LoginFailHandler;
import com.lvcoding.sec3.secdemo3.validatecode.parent.ValidateCodeProcessor;
import com.lvcoding.sec3.secdemo3.validatecode.sms.SmsCode;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * @description 校验短信验证码过滤器
 * @author  wuyanshen
 */
@Component
public class SmsCheckFilter extends OncePerRequestFilter implements InitializingBean {


    private Set<String> urls = new HashSet<>();

    private LoginFailHandler loginFailHandler;

    public LoginFailHandler getLoginFailHandler() {
        return loginFailHandler;
    }

    public void setLoginFailHandler(LoginFailHandler loginFailHandler) {
        this.loginFailHandler = loginFailHandler;
    }

    private AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        boolean action = false;
        for(String url: urls) {
            if(antPathMatcher.match(url, request.getRequestURI())) {
                action = true;
            }
        }

        if(action) {
            try {
                validate(new ServletWebRequest(request, response));
            } catch (ValidateCodeException e) {
                loginFailHandler.onAuthenticationFailure(request, response, e);
                return;
            }
        }

        filterChain.doFilter(request, response);

    }

    @Override
    public void afterPropertiesSet() throws ServletException {
        urls.add("/auth/mobile");
    }

    private void validate(ServletWebRequest request) throws ServletRequestBindingException {
        HttpSession session = request.getRequest().getSession();
        SmsCode codeInSession = (SmsCode) session.getAttribute(ValidateCodeProcessor.SESSION_KEY_PREFIX + "SMS");


        String codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(), "smsCode");

        if(StrUtil.isBlank(codeInRequest)) {
            throw new ValidateCodeException("验证码不能为空");
        }

        if(codeInSession == null) {
            throw new ValidateCodeException("验证码不存在");
        }

        if(codeInSession.isExpired()) {
            throw new ValidateCodeException("验证码已过期");
        }

        if(!StrUtil.equals(codeInSession.getCode(), codeInRequest)) {
            throw new ValidateCodeException("验证码不匹配");
        }

        session.removeAttribute(ValidateCodeProcessor.SESSION_KEY_PREFIX + "SMS");

    }
}
